import React, {Component} from "react";
import {Button, Form, Input} from "antd";
import {connect} from "react-redux";
import {createResetEmail} from '../../action';

import formItemLayout from '../../constant/formItemLayout'
import {FormattedMessage} from "react-intl";

const FormItem = Form.Item;

class EmailEditor extends Component {
  handleSubmitClick = () => {
    this.props.form.validateFields((errors,values) => {
      if(!errors){
        this.props.createResetEmail({
          email: values.newEmail
        })
      }
    })
  };

  handleValidator = (rule, value, callback) => {
    const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]*.){1,63}[a-z0-9]+$/
    if (reg.test(value)) {
      return callback()
    }
    return callback('邮箱格式有误！')
  }

  render = () => {
    const isPending = this.props.emailResetStatus.status === 'PENDING';
    const {getFieldDecorator} = this.props.form;

    return (
      <Form className="email-form">
        <FormItem {...formItemLayout}
                  label={<FormattedMessage id='新邮箱' />}>
          {getFieldDecorator('newEmail', {
            rules: [
              {validator: this.handleValidator},
              {required: true, message: <FormattedMessage id='邮箱不能为空' />}
            ],
          })(
            isPending ? (<span>{this.props.emailResetStatus.email}</span>) : (<Input type="email" placeholder="email"/>)
          )}
        </FormItem>

        <FormItem>
          <Button type="primary" className="submit-email-button" htmlType="submit"
                  disabled={isPending}
                  onClick={this.handleSubmitClick}
          ><FormattedMessage id='提交' /></Button>
          {isPending && <p><FormattedMessage id='我们已经向您的邮箱发送了确认邮件，请您前往认证！' /></p>}
        </FormItem>
      </Form>
    )
  };
}


const mapStateToProps = state => ({
  emailResetStatus: state.emailResetStatus
});

const mapDispatchToProps = dispatch => ({
  createResetEmail: data => dispatch(createResetEmail(data))
});

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(EmailEditor));


